<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 人事管理系统</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Bootstrap图标 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .navbar-brand {
            font-weight: bold;
            font-size: 1.5rem;
        }
        .footer {
            margin-top: 50px;
            padding: 20px 0;
            color: #6c757d;
            border-top: 1px solid #dee2e6;
        }
        .table-actions {
            white-space: nowrap;
        }
        .search-bar {
            margin-bottom: 20px;
        }
        .pagination {
            justify-content: center;
            margin-top: 20px;
        }
        .badge-pill {
            margin-right: 5px;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div th:replace="~{layout/header :: navbar(active='user')}"></div>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>用户管理</h2>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                        <i class="bi bi-plus-circle me-1"></i>新增用户
                    </button>
                </div>
                
                <!-- 搜索栏 -->
                <div class="card search-bar">
                    <div class="card-body">
                        <form id="searchForm" class="row g-3">
                            <div class="col-md-4">
                                <label for="username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary me-2">
                                    <i class="bi bi-search me-1"></i>搜索
                                </button>
                                <button type="button" class="btn btn-secondary" id="resetBtn">
                                    <i class="bi bi-arrow-counterclockwise me-1"></i>重置
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 用户列表 -->
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>用户名</th>
                                        <th>邮箱</th>
                                        <th>角色</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="userTableBody">
                                    <!-- 用户数据通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUserModalLabel">新增用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        <div class="mb-3">
                            <label for="addUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="addUsername" name="username" required>
                        </div>
                        <div class="mb-3">
                            <label for="addPassword" class="form-label">密码</label>
                            <input type="password" class="form-control" id="addPassword" name="password" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色</label>
                            <div id="addRoleCheckboxes" class="border rounded p-2">
                                <!-- 角色选项将通过JavaScript动态加载 -->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editUserModalLabel">编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <input type="hidden" id="editUserId" name="id">
                        <div class="mb-3">
                            <label for="editUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="editUsername" name="username" required readonly>
                            <small class="text-muted">用户名不可修改</small>
                        </div>
                        <div class="mb-3">
                            <label for="editPassword" class="form-label">密码</label>
                            <input type="password" class="form-control" id="editPassword" name="password" placeholder="留空则不修改密码">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色</label>
                            <div id="editRoleCheckboxes" class="border rounded p-2">
                                <!-- 角色选项将通过JavaScript动态加载 -->
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="updateUserBtn">更新</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteUserModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除这个用户吗？此操作不可逆。</p>
                    <input type="hidden" id="deleteUserId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <div th:replace="~{layout/footer :: footer}"></div>
    
    <!-- 通用脚本 -->
    <div th:replace="~{layout/footer :: scripts}"></div>
    
    <!-- 用户管理脚本 -->
    <script>
        $(document).ready(function() {
            // 加载用户列表
            function loadUsers() {
                // 发送AJAX请求获取用户列表
                $.ajax({
                    url: '/users/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const users = response.data;
                            
                            // 清空表格
                            $('#userTableBody').empty();
                            
                            // 遍历用户数据，构建表格行
                            if (users && users.length > 0) {
                                users.forEach(function(user) {
                                    // 构建角色标签
                                    let roleLabels = '';
                                    if (user.roles && user.roles.length > 0) {
                                        user.roles.forEach(function(role) {
                                            roleLabels += `<span class="badge bg-primary badge-pill">${role.name}</span>`;
                                        });
                                    } else {
                                        roleLabels = '<span class="text-muted">无角色</span>';
                                    }
                                    
                                    // 格式化日期时间
                                    const createdAt = user.created_at ? new Date(user.created_at).toLocaleString() : '-';
                                    
                                    const row = `
                                        <tr>
                                            <td>${user.id}</td>
                                            <td>${user.username}</td>
                                            <td>${user.email || '-'}</td>
                                            <td>${roleLabels}</td>
                                            <td>${createdAt}</td>
                                            <td class="table-actions">
                                                <button class="btn btn-sm btn-primary edit-user" data-id="${user.id}">
                                                    <i class="bi bi-pencil"></i> 编辑
                                                </button>
                                                <button class="btn btn-sm btn-danger delete-user" data-id="${user.id}">
                                                    <i class="bi bi-trash"></i> 删除
                                                </button>
                                            </td>
                                        </tr>
                                    `;
                                    $('#userTableBody').append(row);
                                });
                            } else {
                                $('#userTableBody').append('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
                            }
                        } else {
                            alert('加载用户列表失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('加载用户列表失败，请稍后再试');
                    }
                });
            }
            
            // 加载角色列表到复选框组
            function loadRoleCheckboxes(containerId) {
                $.ajax({
                    url: '/roles/list',
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const roles = response.data;
                            const $container = $(`#${containerId}`);
                            
                            // 清空容器
                            $container.empty();
                            
                            // 添加角色复选框
                            if (roles && roles.length > 0) {
                                roles.forEach(function(role) {
                                    const checkboxHtml = `
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" 
                                                value="${role.id}" id="${containerId}_${role.id}" 
                                                name="roleIds">
                                            <label class="form-check-label" for="${containerId}_${role.id}">
                                                ${role.name}
                                            </label>
                                        </div>
                                    `;
                                    $container.append(checkboxHtml);
                                });
                            } else {
                                $container.append('<div class="text-muted">暂无角色数据</div>');
                            }
                        } else {
                            alert('加载角色列表失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('加载角色列表失败，请稍后再试');
                    }
                });
            }
            
            // 初始加载用户列表
            loadUsers();
            
            // 新增用户模态框显示时加载角色选项
            $('#addUserModal').on('show.bs.modal', function() {
                loadRoleCheckboxes('addRoleCheckboxes');
                // 清空表单
                $('#addUserForm')[0].reset();
            });
            
            // 编辑用户模态框显示时加载角色选项
            $('#editUserModal').on('show.bs.modal', function() {
                loadRoleCheckboxes('editRoleCheckboxes');
            });
            
            // 保存新用户
            $('#saveUserBtn').click(function() {
                const username = $('#addUsername').val();
                const password = $('#addPassword').val();
                const roleIds = [];
                
                // 获取所有选中的角色ID
                $('#addRoleCheckboxes input[type="checkbox"]:checked').each(function() {
                    roleIds.push($(this).val());
                });
                
                if (!username || !password || roleIds.length === 0) {
                    alert('请填写完整的用户信息，并至少选择一个角色');
                    return;
                }
                
                const userData = {
                    username: username,
                    password: password,
                    roleIds: roleIds.map(id => parseInt(id))
                };
                
                $.ajax({
                    url: '/users',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#addUserModal').modal('hide');
                            // 重新加载用户列表
                            loadUsers();
                            alert('用户添加成功');
                        } else {
                            alert('用户添加失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('用户添加失败，请稍后再试');
                    }
                });
            });
            
            // 编辑用户按钮点击事件
            $(document).on('click', '.edit-user', function() {
                const userId = $(this).data('id');
                
                // 获取用户详情
                $.ajax({
                    url: '/users/' + userId,
                    type: 'GET',
                    success: function(response) {
                        if (response.code === 1) {
                            const user = response.data;
                            $('#editUserId').val(user.id);
                            $('#editUsername').val(user.username);
                            // 密码不回显，留空
                            $('#editPassword').val('');
                            
                            // 延迟设置角色复选框，确保角色选项已加载
                            setTimeout(function() {
                                if (user.roles && user.roles.length > 0) {
                                    // 先取消所有选中状态
                                    $('#editRoleCheckboxes input[type="checkbox"]').prop('checked', false);
                                    // 设置用户已有的角色为选中状态
                                    user.roles.forEach(function(role) {
                                        $(`#editRoleCheckboxes_${role.id}`).prop('checked', true);
                                    });
                                }
                                $('#editUserModal').modal('show');
                            }, 300);
                        } else {
                            alert('获取用户详情失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('获取用户详情失败，请稍后再试');
                    }
                });
            });
            
            // 更新用户
            $('#updateUserBtn').click(function() {
                const id = $('#editUserId').val();
                const username = $('#editUsername').val();
                const password = $('#editPassword').val();
                const roleIds = [];
                
                // 获取所有选中的角色ID
                $('#editRoleCheckboxes input[type="checkbox"]:checked').each(function() {
                    roleIds.push($(this).val());
                });
                
                if (!username || roleIds.length === 0) {
                    alert('请填写完整的用户信息，并至少选择一个角色');
                    return;
                }
                
                const userData = {
                    id: parseInt(id),
                    username: username,
                    roleIds: roleIds.map(id => parseInt(id))
                };
                
                // 只有当密码字段不为空时，才包含密码
                if (password) {
                    userData.password = password;
                }
                
                $.ajax({
                    url: '/users',
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#editUserModal').modal('hide');
                            // 重新加载用户列表
                            loadUsers();
                            alert('用户更新成功');
                        } else {
                            alert('用户更新失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('用户更新失败，请稍后再试');
                    }
                });
            });
            
            // 删除用户按钮点击事件
            $(document).on('click', '.delete-user', function() {
                const userId = $(this).data('id');
                $('#deleteUserId').val(userId);
                $('#deleteUserModal').modal('show');
            });
            
            // 确认删除用户
            $('#confirmDeleteBtn').click(function() {
                const userId = $('#deleteUserId').val();
                
                $.ajax({
                    url: '/users/' + userId,
                    type: 'DELETE',
                    success: function(response) {
                        if (response.code === 1) {
                            // 关闭模态框
                            $('#deleteUserModal').modal('hide');
                            // 重新加载用户列表
                            loadUsers();
                            alert('用户删除成功');
                        } else {
                            alert('用户删除失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('用户删除失败，请稍后再试');
                    }
                });
            });
            
            // 搜索表单提交
            $('#searchForm').submit(function(event) {
                event.preventDefault();
                const username = $('#username').val();
                
                if (username) {
                    // 实现简单的前端过滤（如果后端提供搜索API则改为调用API）
                    $.ajax({
                        url: '/users/list',
                        type: 'GET',
                        success: function(response) {
                            if (response.code === 1) {
                                const users = response.data;
                                // 过滤用户
                                const filteredUsers = users.filter(user => 
                                    user.username.toLowerCase().includes(username.toLowerCase())
                                );
                                
                                // 清空表格
                                $('#userTableBody').empty();
                                
                                // 显示过滤结果
                                if (filteredUsers && filteredUsers.length > 0) {
                                    filteredUsers.forEach(function(user) {
                                        // 构建角色标签
                                        let roleLabels = '';
                                        if (user.roles && user.roles.length > 0) {
                                            user.roles.forEach(function(role) {
                                                roleLabels += `<span class="badge bg-primary badge-pill">${role.name}</span>`;
                                            });
                                        } else {
                                            roleLabels = '<span class="text-muted">无角色</span>';
                                        }
                                        
                                        // 格式化日期时间
                                        const createdAt = user.created_at ? new Date(user.created_at).toLocaleString() : '-';
                                        
                                        const row = `
                                            <tr>
                                                <td>${user.id}</td>
                                                <td>${user.username}</td>
                                                <td>${user.email || '-'}</td>
                                                <td>${roleLabels}</td>
                                                <td>${createdAt}</td>
                                                <td class="table-actions">
                                                    <button class="btn btn-sm btn-primary edit-user" data-id="${user.id}">
                                                        <i class="bi bi-pencil"></i> 编辑
                                                    </button>
                                                    <button class="btn btn-sm btn-danger delete-user" data-id="${user.id}">
                                                        <i class="bi bi-trash"></i> 删除
                                                    </button>
                                                </td>
                                            </tr>
                                        `;
                                        $('#userTableBody').append(row);
                                    });
                                } else {
                                    $('#userTableBody').append('<tr><td colspan="6" class="text-center">没有找到匹配的用户</td></tr>');
                                }
                            }
                        }
                    });
                } else {
                    loadUsers();
                }
            });
            
            // 重置按钮点击事件
            $('#resetBtn').click(function() {
                $('#username').val('');
                loadUsers();
            });
        });
    </script>
</body>
</html> 